// script.js

const container = document.getElementById("imageContainer");
const canvas = document.getElementById("annotationCanvas");
const ctx = canvas.getContext("2d");
const videoPlayer = document.getElementById("remotevideo");

const closePathButton = document.getElementById("closePathButton");

let annotations = [];
let currAnnoIndex = -1;

let dragging = false;
let selectedPointIndex = null;
let scale = 1;
let isMiddleMouseDown = false;

let oriPointRadius = 4;
let pointRadius = oriPointRadius;
let oriLineWidth = 2;
let lineWidth = oriLineWidth;

let oriImageWidth = null;
let oriImageHeight = null;

let prevMouseX = null;
let prevMouseY = null;

let closePath = false;

const insertModeButton = document.getElementById("insertModeButton");
let insertMode = false;

oriImageWidth = videoPlayer.width;
oriImageHeight = videoPlayer.height;
canvas.width = videoPlayer.width;
canvas.height = videoPlayer.height;
createNewAnnotation();

canvas.style.display = "none";
const playPauseButton = document.getElementById("playPauseButton");

// ****************视频播放按钮**********************
playPauseButton.addEventListener("click", function() {
    if (videoPlayer.paused) {
        videoPlayer.style.display = "block";
        videoPlayer.play();
        canvas.style.display = "none";
    } else {
        videoPlayer.pause();
        clearAnnotations(); // 清除标注信息
        createNewAnnotation();
        captureVideoFrame();
        videoPlayer.style.display = "none";
        canvas.style.display = "block";
    }
});

// ****************视频暂停截图**********************
function clearAnnotations() {
    annotations = [];
    currAnnoIndex = -1;
    scale = 1;
}

function captureVideoFrame() {
    ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);  
}

// ****************插入模式按钮**********************
insertModeButton.addEventListener("click", function () {
    insertMode = !insertMode;
    insertModeButton.textContent = insertMode ? "Exit Insert Mode" : "Insert Mode";
});

// ****************闭合标注按钮**********************
closePathButton.addEventListener("click", function () {
    closePath = true;
    annotations[currAnnoIndex].isClose = true;
    updateDrawing();
    createNewAnnotation();
});

// ****************标注列表**********************
// function updateAnnotationsList() {
//     const annotationsList = document.getElementById("annotationsList");
//     annotationsList.innerHTML = "<h2>Annotations List</h2>";

//     annotations.forEach((anno, index) => {
//         const listItem = document.createElement("div");
//         listItem.innerHTML = `<strong>Annotation ${index + 1}:</strong>`;

//         const pointsList = document.createElement("ul");
//         anno.relativetePoints.forEach(point => {
//             const pointItem = document.createElement("li");
//             pointItem.textContent = `(${point.x.toFixed(2)}, ${point.y.toFixed(2)})`;
//             pointsList.appendChild(pointItem);
//         });

//         listItem.appendChild(pointsList);
//         annotationsList.appendChild(listItem);
//     });
// }


// ***************添加新的标注********************

function createNewAnnotation() {
    insertMode = false; // 退出插入模式
    insertModeButton.textContent = "Insert Mode"; // 更新插入模式按钮文本

    let anno = { relativetePoints: [], isClose: false, pointColor: "#FF0000", lineColor: "#00FF00" };
    annotations.push(anno);
    currAnnoIndex = currAnnoIndex + 1;
}

// *******************************************
// 画布鼠标中键按下事件
canvas.addEventListener("mousedown", function (e) {
    if (e.button != 1) return;
    e.preventDefault();
    isMiddleMouseDown = true;

    prevMouseX = e.clientX;
    prevMouseY = e.clientY;

    document.addEventListener("mousemove", drag);
    document.addEventListener("mouseup", stopDragging);
});

function drag(e) {
    if (isMiddleMouseDown) {
        const deltaX = e.clientX - prevMouseX;
        const deltaY = e.clientY - prevMouseY;

        // image.style.left = `${image.offsetLeft + deltaX}px`;
        // image.style.top = `${image.offsetTop + deltaY}px`;
        canvas.style.left = `${canvas.offsetLeft + deltaX}px`;
        canvas.style.top = `${canvas.offsetTop + deltaY}px`;

        prevMouseX = e.clientX;
        prevMouseY = e.clientY;
    }
}

function stopDragging() {
    isMiddleMouseDown = false;
    document.removeEventListener("mousemove", drag);
    document.removeEventListener("mouseup", stopDragging);
}

//**********************************************************************************//
// 画布缩放事件
canvas.addEventListener("wheel", function (e) {
    e.preventDefault();

    scale = scale + e.deltaY * -0.003;
    scale = Math.min(Math.max(0.2, scale), 8);

    // image.width = oriImageWidth * scale;
    // image.height = oriImageHeight * scale;

    canvas.width = oriImageWidth * scale;
    canvas.height = oriImageHeight * scale;
    updateDrawing();
});

// 画布鼠标左键按下事件
canvas.addEventListener("mousedown", function (e) {
    if (e.button != 0) return;
    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    if (insertMode || e.ctrlKey) {
        insertPointBetween(mouseX, mouseY);
    } else {
        selectOrAddPoint(mouseX, mouseY);
    }
});

function insertPointBetween(mouseX, mouseY) {
    for (let annoIndex = 0; annoIndex < annotations.length; annoIndex++) {
        let points = updatePoints(annotations[annoIndex].relativetePoints);
        if (points.length < 2) return;

        for (let i = 1; i < points.length + 1; i++) {
            const point1 = points[i - 1];
            const point2 = points[i % points.length];

            const distanceToLine = Math.abs(
                (point2.y - point1.y) * mouseX - (point2.x - point1.x) * mouseY + point2.x * point1.y - point2.y * point1.x
            ) / Math.sqrt(Math.pow(point2.y - point1.y, 2) + Math.pow(point2.x - point1.x, 2));

            const midpoint = {
                x: (point1.x + point2.x) / 2,
                y: (point1.y + point2.y) / 2
            };
            const distanceToMidpoint = Math.sqrt(Math.pow(mouseX - midpoint.x, 2) + Math.pow(mouseY - midpoint.y, 2));

            if (distanceToLine < 5 && distanceToMidpoint < 20) {
                const x = mouseX / canvas.width;
                const y = mouseY / canvas.height;
                annotations[annoIndex].relativetePoints.splice(i, 0, { x, y });
                updateDrawing();
                break;
            }
        }
    }
}

function selectOrAddPoint(mouseX, mouseY) {
    for (let annoIndex = 0; annoIndex < annotations.length; annoIndex++) {
        let points = updatePoints(annotations[annoIndex].relativetePoints);

        for (let i = 0; i < points.length; i++) {
            const point = points[i];
            const distance = Math.sqrt(Math.pow(mouseX - point.x, 2) + Math.pow(mouseY - point.y, 2));

            if (distance < 10) {
                dragging = true;
                selectedPointIndex = { annoIndex: annoIndex, pointIndex: i };
                break;
            }
        }
    }

    if (selectedPointIndex == null) {
        const x = mouseX / canvas.width;
        const y = mouseY / canvas.height;
        annotations[currAnnoIndex].relativetePoints.push({ x, y });
        updateDrawing();
    }
}

// 画布鼠标拖动事件
canvas.addEventListener("mousemove", function (e) {
    if (dragging && selectedPointIndex !== null) {
        const rect = canvas.getBoundingClientRect();
        const x = (e.clientX - rect.left) / canvas.width;
        const y = (e.clientY - rect.top) / canvas.height;
        let annoIndex = selectedPointIndex.annoIndex;
        let pointIndex = selectedPointIndex.pointIndex;
        annotations[annoIndex].relativetePoints[pointIndex] = { x, y };
        updateDrawing();
    }
});

// 画布鼠标松开事件
canvas.addEventListener("mouseup", function (e) {
    if (e.button != 0) return;
    dragging = false;
    selectedPointIndex = null;

    updateDrawing();
});

// 更新画布内容
function updateDrawing() {
    clearCanvas();
    ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
    drawLines();
    drawPoints();
    //updateAnnotationsList();
}

// 相对坐标转为绝对坐标
function updatePoints(relativetePoints) {
    const rect = canvas.getBoundingClientRect();

    let points = relativetePoints.map(relativetePoint => ({
        x: relativetePoint.x * canvas.width,
        y: relativetePoint.y * canvas.height
    }));

    return points;
}

// 清空画布内容
function clearCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function drawLines() {
    annotations.forEach(anno => {
        let points = updatePoints(anno.relativetePoints);

        if (points.length < 2) return;

        ctx.beginPath();

        ctx.moveTo(points[0].x, points[0].y);

        for (let i = 1; i < points.length; i++) {
            ctx.lineTo(points[i].x, points[i].y);
        }

        if (anno.isClose) {
            ctx.closePath();
            ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
            ctx.fill();
        }
        ctx.strokeStyle = anno.lineColor;
        ctx.lineWidth = lineWidth;
        ctx.stroke();
    });
}

function drawPoints() {
    for (let annoIndex = 0; annoIndex < annotations.length; annoIndex++) {
        let points = updatePoints(annotations[annoIndex].relativetePoints);
        for (let i = 0; i < points.length; i++) {
            ctx.beginPath();
            ctx.arc(points[i].x, points[i].y, pointRadius, 0, 2 * Math.PI);
            if (selectedPointIndex != null && annoIndex == selectedPointIndex.annoIndex && i === selectedPointIndex.pointIndex) {
                ctx.fillStyle = "#00FF00";
            } else {
                ctx.fillStyle = annotations[annoIndex].pointColor;
            }
            ctx.fill();
            ctx.stroke();
        }
    }
}
